package com.dhecp.project.system.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.constant.Constants;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.StringUtils;
import com.dhecp.common.utils.security.RsaUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.framework.shiro.service.SysPasswordService;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.system.domain.SysRoleInfo;
import com.dhecp.project.system.domain.SysUserBindRole;
import com.dhecp.project.system.domain.SysUserInfo;
import com.dhecp.project.system.domain.SysUserInfoSimple;
import com.dhecp.project.system.mapper.SysOrganizationInfoMapper;
import com.dhecp.project.system.mapper.SysUserInfoMapper;
import com.dhecp.project.system.mapper.SysUserInfoSimpleMapper;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import com.dhecp.project.system.service.SysUserInfoService;

/**
 * 用户 业务层处理
 *
 * @author DH-Xxj
 */
@Service
public class SysUserInfoServiceImpl implements SysUserInfoService {
    private String moduleTable = ModuleTable.USER_INFO;
    private String moduleTableForUserDept = ModuleTable.USER_DEPT_INFO;

    @Autowired
    private SysUserInfoMapper userInfoMapper;

    @Autowired
    private SysUserInfoSimpleMapper userInfoSimpleMapper;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private SysOrganizationInfoMapper organizationInfoMapper;

    /**
     * 验证用户名和密码
     *
     * @param userId
     * @param passWord（传空）
     * @return UserInfo
     * @author DH-Xxj
     */
    @Override
    public SysUserInfo queryByUseridAndPass(String userId, String passWord) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", userId);
        params.put("userPassWord", passWord);
        return userInfoMapper.findByUserIdAndPass(params);
    }

    /**
     * 验证用户名和密码
     *
     * @param userId       用户编号
     * @param userPassWord 加密后的用户密码
     * @return
     * @author DH-Xxj
     */
    public SysUserInfo checkedUserIdAndPass(String userId, String userPassWord) {
        return userInfoMapper.checkedUserIdAndPass(userId, userPassWord);
    }

    /**
     * 验证用户名和二级密码
     *
     * @param userId        用户编号
     * @param userPassWord2 加密后的用户二级密码
     * @return
     * @author DH-Xxj
     */
    public SysUserInfo checkedUserIdAndPass2(String userId, String userPassWord2) {
        return userInfoMapper.checkedUserIdAndPass2(userId, userPassWord2);
    }


    /**
     * 拓展用户登录验证
     *
     * @param params
     * @return String (返回异常提示信息，返回空代表无异常)
     * @author DH-Xxj
     */
    @Override
    public String queryUserLoginException(Map<String, Object> params) {
        return userInfoMapper.findUserLoginException(params);
    }

    /**
     * 通过用户编号查询用户信息
     *
     * @param userId
     * @return 实体-UserInfo
     * @author DH-Xxj
     */
    @Override
    public SysUserInfo queryByUserId(String userId) {
        return userInfoMapper.findByUserId(userId);
    }

    /**
     * 通过用户企业微信ID查询用户信息
     *
     * @param enWeChatId
     * @return 实体-UserInfo
     * @author DH-Xxj
     */
    @Override
    public List<SysUserInfo> queryByWeChatId(String enWeChatId) {
        return userInfoMapper.findByWeChatId(enWeChatId);
    }

    /**
     * 按条件查询用户列表 —— 精简数据
     *
     * @param wherestrhand 自行组装的查询条件语句
     * @param nowherestr   若存在（任意值），表示不进行条件过滤
     * @param nodatascode  若存在（任意值），表示不进行数据权限控制
     * @return List-UserInfo
     * @throws Exception
     * @author DH-Xxj
     */
    @Override
    public List<SysUserInfoSimple> queryUserSimpleList(Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));        //常规查询条件SQL语句
        if (params.get("field") == null || params.get("field") == "") {
            String orderBy = "userId asc";
            PageUtils.startPageOrder(orderBy);
        } else {
            PageUtils.startPage();
        }
        return userInfoSimpleMapper.findUserSimpleList(params);
    }

    /**
     * 按条件查询指定角色类型（客户销售）用户列表 —— 精简数据
     *
     * @param roleType 必要参数，示例：customerGUser（客户销售）、All（查询全部）、SW（商务类角色）、（XS）销售类角色，具体类型在表TS_RoleGuidType中查看和配置
     * @param gClient  可选参数，客户编号，当roleType=‘customerGUser’时，必需传对应客户编号
     * @return
     * @throws Exception
     * @author DH-Xxj
     */
    @Override
    public List<SysUserInfoSimple> queryRoleTypeUserSimpleList(Map<String, Object> params) throws Exception {
        String roleType = "";
        params.put("moduleTable", moduleTable);
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));        //常规查询条件SQL语句
        if (params.get("roleType") == null || params.get("roleType") == "") {
            roleType = "All";
            params.put("roleType", roleType);
        } else {
            roleType = params.get("roleType").toString();
        }
        if (params.get("field") == null || params.get("field") == "") {
            String orderBy = "userId asc";
            PageUtils.startPageOrder(orderBy);
        } else {
            PageUtils.startPage();
        }

        if ("customerGUser".equals(roleType)) {
            if (params.get("gClient") == null || params.get("gClient") == "") {
                params.put("gClient", "no");
            }
            return userInfoSimpleMapper.findCustomerGUserSimpleList(params);
        } else {
            return userInfoSimpleMapper.findRoleTypeUserSimpleList(params);
        }
    }

    /**
     * 通过daNid查询用户信息
     *
     * @param daNid 必要参数：档案nid号
     * @return List - SysUserInfoSimple
     * @throws Exception
     * @author DH-Xxj
     */
    @Override
    public List<SysUserInfoSimple> queryUserSimpleListByDaNid(Map<String, Object> params) throws Exception {
        if (params.get("daNid") == null || params.get("daNid") == "") {
            params.put("daNid", "daNid");
        }
        params.put("mandator", ShiroUtils.getMandatorId());
        return userInfoSimpleMapper.findUserByDaNid(params);
    }

    /**
     * 按条件查询用户列表
     *
     * @param params
     * @param nowherestr  若存在（任意值），表示不进行条件过滤
     * @param nodatascode 若存在（任意值），表示不进行数据权限控制
     * @return List-UserInfo
     * @throws Exception
     * @author DH-Xxj
     */
    @Override
    public List<SysUserInfo> queryUserList(Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));        //t1表常规查询条件SQL语句
        String datascodet1 = dictionaryForFieldService.getDataScode(params);        //t1表数据权限查询条件SQL语句

        params.put("jurisdictionModuleTable", params.get("moduleTable"));//权限条件使用，权限设置中【指定权限】绑定的ModuleTable；多表查询时通常为主表，即设置用户权限的表
        params.put("moduleTable", moduleTableForUserDept); //【权限字段】绑定的ModuleTable，实际数据权限作用的表，多表查询时通常为需要参与权限控制的关联表
        params.put(DataFiltering.TABLE_ALIAS, "t3");    //查询表别名
        params.put("wherestrt3", dictionaryForFieldService.getWhereStr(params));        //t3表常规查询条件SQL语句
        String datascodet3 = dictionaryForFieldService.getDataScode(params);            //t3表数据权限查询条件SQL语句

        String datascode = "";
        if ("".equals(datascodet1)) {
            datascode = datascodet3;
        } else {
            if ("".equals(datascodet3)) {
                datascode = datascodet1;
            } else {
                datascode = "(" + datascodet1 + " or " + datascodet3 + ")";
            }
        }
        params.put("datascode", datascode);    //数据权限查询条件SQL语句
        params.put("mandator", ShiroUtils.getMandatorId());

        if (params.get("field") == null || params.get("field") == "") {
            String orderBy = "userId asc";
            PageUtils.startPageOrder(orderBy);
        } else if ("userleveltext".equals(params.get("field").toString().toLowerCase())) {
            String orderBy = "";
            if (params.get("order") != null && "desc".equals(params.get("order").toString().toLowerCase())) {
                orderBy = "userLevel desc";
            } else {
                orderBy = "userLevel asc";
            }
            PageUtils.startPageOrder(orderBy);
        } else {
            PageUtils.startPage();
        }
        return userInfoMapper.findUserList(params);
    }

    /**
     * 查询拥有指定角色的用户列表
     *
     * @param roleguid    必要参数：角色guid号
     * @param nowherestr  若存在（任意值），表示不进行条件过滤
     * @param nodatascode 若存在（任意值），表示不进行数据权限控制
     * @return List-UserInfo
     * @throws Exception
     * @author DH-Xxj
     */
    @Override
    public List<SysUserInfo> queryUserListByRoleGuid(Map<String, Object> params) throws Exception {
        if (params.get("roleguid") == null || params.get("roleguid") == "") {
            //角色guid,必要查询条件
            params.put("roleguid", "000000");
        } else {
            params.put("moduleTable", moduleTable);
            params.put(DataFiltering.TABLE_ALIAS, "t1");
            params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));        //t1表常规查询条件SQL语句

            params.put("moduleTable", moduleTableForUserDept);
            params.put(DataFiltering.TABLE_ALIAS, "t3");    //查询表别名
            params.put("wherestrt3", dictionaryForFieldService.getWhereStr(params));        //t3表常规查询条件SQL语句
        }
        params.put("mandator", ShiroUtils.getMandatorId());
        return userInfoMapper.findUserListByRoleGuid(params);
    }

    /**
     * 通过用户编号或用户名称查询用户信息
     *
     * @param params
     * @param userIdOrUserName 必要参数：用户编号 或 用户名称
     * @return
     * @author DH-Xxj
     */
    @Override
    public List<SysUserInfo> queryUserListByUserIdOrUserName(Map<String, Object> params) {
        String userIdOrUserName = params.get("userIdOrUserName").toString();
        if (params.get("field") == null || params.get("field") == "") {
            String orderBy = "userId asc";
            PageUtils.startPageOrder(orderBy);
        } else {
            PageUtils.startPage();
        }
        return userInfoMapper.findByUserIdOrUserName(userIdOrUserName);
    }

    /**
     * 查询指定机构下的用户列表
     *
     * @param orgPathAll 必要参数：指定机构全路径
     * @return List-UserInfo
     * @author DH-Xxj
     */
    @Override
    public List<SysUserInfo> queryUserListByOrgPathAll(Map<String, Object> params) {
        params.put("mandator", ShiroUtils.getMandatorId());
        if (params.get("field") == null || params.get("field") == "") {
            String orderBy = "userId asc";
            PageUtils.startPageOrder(orderBy);
        } else {
            PageUtils.startPage();
        }
        return userInfoMapper.findUserListByOrgPathAll(params);
    }

    /**
     * 查询指定机构的管理者列表
     *
     * @param orgPathAll 必要参数：指定机构全路径
     * @return List-UserInfo
     * @author DH-Xxj
     */
    @Override
    public List<SysUserInfo> queryManagersAllListByOrgPathAll(Map<String, Object> params) {
        params.put("mandator", ShiroUtils.getMandatorId());
        return userInfoMapper.findManagersAllListByOrgPathAll(params);
    }

    /**
     * 查询指定资料文件夹的管理者列表
     *
     * @param guid 必要参数：资料文件夹guid
     * @return List-UserInfo
     * @author DH-Xxj
     */
    @Override
    public List<SysUserInfo> queryManagersAllListByGuid(Map<String, Object> params) {
        params.put("mandator", ShiroUtils.getMandatorId());
        return userInfoMapper.findManagersAllListByGuid(params);
    }

    /**
     * 按条件查询超级管理员列表
     *
     * @param params
     * @return List-UserInfo
     * @throws Exception
     * @author DH-Xxj
     */
    @Override
    public List<SysUserInfo> querySuperUserList(Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        params.put(DataFiltering.TABLE_ALIAS, "t1");
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));        //t1表常规查询条件SQL语句

        params.put("moduleTable", moduleTableForUserDept);
        params.put(DataFiltering.TABLE_ALIAS, "t3");    //查询表别名
        params.put("wherestrt3", dictionaryForFieldService.getWhereStr(params));        //t3表常规查询条件SQL语句

        return userInfoMapper.findSuperUserList(params);
    }

    /**
     * 新增用户信息
     *
     * @param userInfoItems 对应实体类的json格式字符串
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult insertUserInfo(Map<String, Object> params) {
        List<SysUserInfo> userInfoList = JSON.parseArray(params.get("userInfoItems").toString(), SysUserInfo.class);
        if (userInfoList == null || userInfoList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        SysPasswordService sysPasswordService = new SysPasswordService();
        for (SysUserInfo userInfo : userInfoList) {
            if (userInfoMapper.findByUserId(userInfo.getUserId()) != null) {
                return AjaxResult.error("用户编号已经存在，不能重复添加！");
            } else {
                //初始密码设置为用户编号
                String newPassword = sysPasswordService.encryptPassword(userInfo.getUserId(), userInfo.getUserId(), Constants.PASSWORD_SALT);
                String newPassword2 = sysPasswordService.encryptPassword(userInfo.getUserId(), userInfo.getUserId(), Constants.PASSWORD_SALT);
                userInfo.setUserPassWord(newPassword);
                userInfo.setUserPassWord2(newPassword2);
                if (userInfo.getUserLevel() == null) {
                    userInfo.setUserLevel(3);
                }
                userInfo.setCreateUser(ShiroUtils.getUserId());
                userInfo.setCreateTime(new Date());
                userInfo.setUpdateUser(ShiroUtils.getUserId());
                userInfo.setUpdateTime(new Date());
                userInfoMapper.insert(userInfo);
            }
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 分配用户角色
     *
     * @param userId    当前分配角色的用户编码
     * @param infoItems 角色对应实体类的json格式字符串(必要键值：角色编码[guid])
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult insertUserRole(Map<String, Object> params) {
        if (params.get("userId") == null || "".equals(params.get("userId").toString())) {
            return AjaxResult.error("用户编码[userId]不能为空！");
        }
        List<SysRoleInfo> roleInfoList = JSON.parseArray(params.get("infoItems").toString(), SysRoleInfo.class);
        if (roleInfoList == null) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        SysUserBindRole userBindRole = new SysUserBindRole();
        userBindRole.setUserId(params.get("userId").toString());
        userInfoMapper.deleteUserRole(userBindRole);

        for (SysRoleInfo roleInfo : roleInfoList) {
            userBindRole.setRoleguid(roleInfo.getGuid());
            userInfoMapper.insertUserRole(userBindRole);
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 删除用户信息
     *
     * @param userInfoItems 对应实体类的json格式字符串
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult deleteUserInfo(Map<String, Object> params) {
        List<SysUserInfo> userInfoList = JSON.parseArray(params.get("userInfoItems").toString(), SysUserInfo.class);
        if (userInfoList == null || userInfoList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        for (SysUserInfo userInfo : userInfoList) {
            userInfoMapper.deleteUserByUserId(userInfo);
            params.put("orgid", userInfo.getUserId());
            organizationInfoMapper.deleteUserByOrgid(params);
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 删除用户角色
     *
     * @param userBindRoleItems 对应实体类的json格式字符串(用户编码[userId],角色编码[roleguid])
     * @return
     * @author DH-Xxj
     */
    @Override
    public AjaxResult deleteUserRole(Map<String, Object> params) {
        List<SysUserBindRole> userBindRoleList = JSON.parseArray(params.get("userBindRoleItems").toString(), SysUserBindRole.class);
        if (userBindRoleList == null || userBindRoleList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        for (SysUserBindRole userBindRole : userBindRoleList) {
            params.put("userId", userBindRole.getUserId());
            params.put("roleguid", userBindRole.getRoleguid());

            if (params.get("userId") == null || "".equals(params.get("userId").toString())) {
                return AjaxResult.error("用户编码[userId]不能为空！");
            }
            if (params.get("roleguid") == null || "".equals(params.get("roleguid").toString())) {
                return AjaxResult.error("角色编码[roleguid]不能为空！");
            }
            userInfoMapper.deleteUserRole(userBindRole);
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 修改 始终允许浏览器登录 字段
     *
     * @param infoItems 对应实体类的json格式字符串，包含属性（userId：用户编号， browserLogin：始终允许浏览器登录）
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateBrowserLogin(Map<String, Object> params) {
        List<SysUserInfo> userInfoList = JSON.parseArray(params.get("infoItems").toString(), SysUserInfo.class);
        if (userInfoList == null || userInfoList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        for (SysUserInfo userInfo : userInfoList) {
            if (userInfo.getUserId() != null && !"".equals(userInfo.getUserId().toString())) {
                userInfo.setUpdateUser(ShiroUtils.getUserId());
                userInfo.setUpdateTime(new Date());
                userInfoMapper.updateBrowserLogin(userInfo);
            } else {
                return AjaxResult.error("缺少用户编号，无法更新数据！");
            }
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 修改用户密码
     *
     * @param upType 修改类型（"resetpwd":重置密码，无需提供原密码；"changepwd":修改密码，需要提供原密码）
     * @param userId 用户编号
     * @param newPwd 新用户密码
     * @param oldPwd 原用户密码，修改密码时需要提供，重置密码时可不提供
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateUserPassWord(Map<String, Object> params) throws Exception {
        if (params.get("upType") == null || params.get("upType") == "") {
            return AjaxResult.error("缺少参数：upType【修改类型】！");
        }
        if (params.get("userId") == null || params.get("userId") == "") {
            return AjaxResult.error("缺少参数：userId【用户编号】！");
        }
        if (params.get("newPwd") == null || params.get("newPwd") == "") {
            return AjaxResult.error("缺少参数：newPwd【新用户密码】！");
        }
        String upType = params.get("upType").toString().toLowerCase();
        String userId = params.get("userId").toString();
        String newPwd = params.get("newPwd").toString();
        newPwd = RsaUtils.decryptByPrivateKey(newPwd);//对前台上传的RAS加密密码进行解密

        SysPasswordService sysPasswordService = new SysPasswordService();
        SysUserInfo userInfo = new SysUserInfo();
        SysUserInfo userInfoChecked = userInfoMapper.findByUserIdAndPass(params);
        if ("resetpwd".equals(upType)) { //重置密码，无需提供原密码,需要管理员才能重置
            int userLevel = ShiroUtils.getSysUser().getUserLevel();    //当前用户管理级别

            if (userInfoChecked == null) {
                return AjaxResult.error("用户【" + userId + "】不存在！");
            } else if (userLevel < 6) {
                return AjaxResult.error("只有管理员才能重置密码！您可以打开密码修改功能，验证原密码后进行修改或联系管理员重置密码！");
            } else {
                String newPassword = sysPasswordService.encryptPassword(userId, newPwd, Constants.PASSWORD_SALT);
                userInfo.setUserPassWord(newPassword);
                userInfo.setUserId(userId);
                userInfo.setUpdateUser(ShiroUtils.getUserId());
                userInfo.setUpdateTime(new Date());
                userInfoMapper.updatePassWord(userInfo);
            }
        } else if ("changepwd".equals(upType)) { //修改密码，需要提供原密码
            if (params.get("oldPwd") == null || params.get("oldPwd") == "") {
                return AjaxResult.error("缺少参数：oldPwd【原用户密码】！");
            }
            String oldPwd = params.get("oldPwd").toString();
            oldPwd = RsaUtils.decryptByPrivateKey(oldPwd);//对前台上传的RAS加密密码进行解密
            String oldPassword = sysPasswordService.encryptPassword(userId, oldPwd, Constants.PASSWORD_SALT);

            if (userInfoChecked == null) {
                return AjaxResult.error("用户【" + userId + "】不存在！");
            } else if (!userInfoChecked.getUserPassWord().toString().equals(oldPassword)) {
                return AjaxResult.error("用户【" + userId + "】的原始密码不正确，请重新输入！");
            } else {
                String newPassword = sysPasswordService.encryptPassword(userId, newPwd, Constants.PASSWORD_SALT);
                userInfo.setUserPassWord(newPassword);
                userInfo.setUserId(userId);
                userInfo.setUpdateUser(ShiroUtils.getUserId());
                userInfo.setUpdateTime(new Date());
                userInfoMapper.updatePassWord(userInfo);
            }
        } else {
            return AjaxResult.error("未知的修改类型[upType]！");
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 修改用户密码-本地操作
     */
    @Override
    public AjaxResult updateUserPassWordLocal(String userId, String newPwd) {

        SysUserInfo userInfo = new SysUserInfo();

        String newPassword = new SysPasswordService().encryptPassword(userId, newPwd, Constants.PASSWORD_SALT);
        userInfo.setUserPassWord(newPassword);
        userInfo.setUserId(userId);
        userInfo.setUpdateUser(ShiroUtils.getUserId());
        userInfo.setUpdateTime(new Date());
        userInfoMapper.updatePassWord(userInfo);
        return AjaxResult.success("操作成功");
    }

    /**
     * 修改二级密码
     *
     * @param upType  修改类型（"resetpwd":重置密码，无需提供原密码；"changepwd":修改密码，需要提供原密码）
     * @param userId  用户编号
     * @param newPwd2 新二级密码
     * @param oldPwd2 原二级密码，修改密码时需要提供，重置密码时可不提供
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateUserPassWord2(Map<String, Object> params) throws Exception {
        if (params.get("upType") == null || params.get("upType") == "") {
            return AjaxResult.error("缺少参数：upType【修改类型】！");
        }
        if (params.get("userId") == null || params.get("userId") == "") {
            return AjaxResult.error("缺少参数：userId【用户编号】！");
        }
        if (params.get("newPwd2") == null || params.get("newPwd2") == "") {
            return AjaxResult.error("缺少参数：newPwd2【新二级密码】！");
        }
        String upType = params.get("upType").toString().toLowerCase();
        String userId = params.get("userId").toString();
        String newPwd2 = params.get("newPwd2").toString();
        newPwd2 = RsaUtils.decryptByPrivateKey(newPwd2);//对前台上传的RAS加密密码进行解密

        SysPasswordService sysPasswordService = new SysPasswordService();
        SysUserInfo userInfo = new SysUserInfo();
        SysUserInfo userInfoChecked = userInfoMapper.findByUserIdAndPass(params);
        if ("resetpwd".equals(upType)) { //重置密码，无需提供原密码,需要管理员才能重置
            int userLevel = ShiroUtils.getSysUser().getUserLevel();    //当前用户管理级别

            if (userInfoChecked == null) {
                return AjaxResult.error("用户【" + userId + "】不存在！");
            } else if (userLevel < 6) {
                return AjaxResult.error("只有管理员才能重置密码！您可以打开密码修改功能，验证原密码后进行修改或联系管理员重置密码！");
            } else {
                String newPassword2 = sysPasswordService.encryptPassword(userId, newPwd2, Constants.PASSWORD_SALT);
                userInfo.setUserPassWord2(newPassword2);
                userInfo.setUserId(userId);
                userInfo.setUpdateUser(ShiroUtils.getUserId());
                userInfo.setUpdateTime(new Date());
                userInfoMapper.updatePassWord2(userInfo);
            }
        } else if ("changepwd".equals(upType)) { //修改密码，需要提供原密码
            if (params.get("oldPwd2") == null || params.get("oldPwd2") == "") {
                return AjaxResult.error("缺少参数：oldPwd2【原二级密码】！");
            }
            String oldPwd2 = params.get("oldPwd2").toString();
            oldPwd2 = RsaUtils.decryptByPrivateKey(oldPwd2);//对前台上传的RAS加密密码进行解密
            String oldPassword2 = sysPasswordService.encryptPassword(userId, oldPwd2, Constants.PASSWORD_SALT);

            if (userInfoChecked == null) {
                return AjaxResult.error("用户【" + userId + "】不存在！");
            } else if (!userInfoChecked.getUserPassWord2().toString().equals(oldPassword2)) {
                return AjaxResult.error("用户【" + userId + "】的原始二级密码不正确，请重新输入！");
            } else {
                String newPassword2 = sysPasswordService.encryptPassword(userId, newPwd2, Constants.PASSWORD_SALT);
                userInfo.setUserPassWord2(newPassword2);
                userInfo.setUserId(userId);
                userInfo.setUpdateUser(ShiroUtils.getUserId());
                userInfo.setUpdateTime(new Date());
                userInfoMapper.updatePassWord2(userInfo);
            }
        } else {
            return AjaxResult.error("未知的修改类型[upType]！");
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 修改用户信息
     *
     * @param userInfoItems 对应实体类的json格式字符串
     * @param upType        修改类型（修改用户信息：upuser，修改用户基础信息：upuserbaseinfo，修改用户皮肤：upskin，修改档案照片：upuserphoto，修改用户头像：upuserpicture）
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateUserInfo(Map<String, Object> params) {
        if (params.get("upType") == null || params.get("upType") == "") {
            return AjaxResult.error("缺少参数：upType【修改类型】！");
        }
        List<SysUserInfo> userInfoList = JSON.parseArray(params.get("userInfoItems").toString(), SysUserInfo.class);
        if (userInfoList == null || userInfoList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        if ("upuser".equals(params.get("upType").toString().toLowerCase())) {
            for (SysUserInfo userInfo : userInfoList) {
                //修改用户信息
                userInfo.setUpdateUser(ShiroUtils.getUserId());
                userInfo.setUpdateTime(new Date());
                userInfoMapper.update(userInfo);
                organizationInfoMapper.updateUserName(userInfo);
            }
        } else if ("upuserbaseinfo".equals(params.get("upType").toString().toLowerCase())) {
            for (SysUserInfo userInfo : userInfoList) {
                SysUserInfo oldUser = userInfoMapper.findByUserId(userInfo.getUserId());
                //修改用户信息
                userInfo.setUpdateUser(ShiroUtils.getUserId());
                userInfo.setUpdateTime(new Date());
                if (userInfo.getUserName()==null || userInfo.getUserName().equals("")){
                    userInfo.setUserName(oldUser.getUserName());
                }
                userInfoMapper.updateUserBaseInfo(userInfo);
                organizationInfoMapper.updateUserName(userInfo);
            }
        } else if ("upskin".equals(params.get("upType").toString().toLowerCase())) {
            for (SysUserInfo userInfo : userInfoList) {
                //修改用户皮肤
                userInfoMapper.updateSkin(userInfo);
            }
        } else if ("upuserphoto".equals(params.get("upType").toString().toLowerCase())) {
            for (SysUserInfo userInfo : userInfoList) {
                //修改档案照片
                userInfoMapper.updateUserPhoto(userInfo);
            }
        } else if ("upuserpicture".equals(params.get("upType").toString().toLowerCase())) {
            for (SysUserInfo userInfo : userInfoList) {
                //修改用户头像
                userInfoMapper.updateUserPicture(userInfo);
            }
        } else if ("userleader".equals(params.get("upType").toString().toLowerCase())) {
            for (SysUserInfo userInfo : userInfoList) {
                //修改上级
                userInfo.setUserLeader(params.get("targetUserId").toString());
                userInfoMapper.updateUserLeader(userInfo);
            }
        } else {
            return AjaxResult.error("未知的修改类型[upType]！");
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 绑定用户档案
     *
     * @param infoItems 对应实体类的json格式字符串，包含属性（userId ：用户编号，daNid ：档案入职信息nid号）
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateUserDaNid(Map<String, Object> params) {
        List<SysUserInfo> userInfoList = JSON.parseArray(params.get("infoItems").toString(), SysUserInfo.class);
        if (userInfoList == null || userInfoList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        for (SysUserInfo userInfo : userInfoList) {
            if (userInfo.getUserId() != null && !"".equals(userInfo.getUserId().toString())) {
                Map<String, Object> userMap = new HashMap<String, Object>();
                userMap.put("userId", userInfo.getUserId());
                userMap.put("daNid", userInfo.getDaNid());
                userMap.put("updateUser", ShiroUtils.getUserId());
                userMap.put("updateTime", new Date());
                userInfoMapper.updateUserDaNid(userMap);
            } else {
                return AjaxResult.error("缺少用户编号，无法更新数据！");
            }
        }
        return AjaxResult.success("操作成功");
    }

    @Override
    public List<SysUserInfo> queryUserListBySync(Map<String, Object> params) {
        return userInfoMapper.findUserList(params);
    }

    @Override
    public AjaxResult updateUserBySyncUnionId(String userId, String syncUnionId, String enWeChatId) {
        if (StringUtils.isEmpty(userId)) {
            return AjaxResult.error("参数[userId]不能为空！");
        }
        //if (StringUtils.isEmpty(syncUnionId)){
        //return AjaxResult.error("参数[syncUnionId]不能为空！");
        // }
        //if (StringUtils.isEmpty(enWeChatId)){
        //return AjaxResult.error("参数[enWeChatId]不能为空！");
        //}
        Map<String, Object> updateParams = new HashMap<>();
        updateParams.put("userId", userId);
        updateParams.put("syncUnionId", syncUnionId);
        updateParams.put("enWeChatId", enWeChatId);
        userInfoMapper.updateUserBySyncUnionId(updateParams);
        return AjaxResult.success("操作成功！");
    }


    @Override
    public String getUserRoleId(String userId) {
        String roleId = "";
        Map<String, Object> getUserRoleId = userInfoMapper.getUserRoleId(userId);
        if(getUserRoleId!=null && getUserRoleId.get("RoleId")!=null){
            roleId = getUserRoleId.get("RoleId").toString();
        }
        return roleId;
    }

    @Override
    public String getUserRouteCode(String userId) {
        String routeCode = "";
        Map<String, Object> getUserRouteCode = userInfoMapper.getUserRouteCode(userId);
        if(getUserRouteCode!=null && getUserRouteCode.get("RouteCode")!=null){
            routeCode = getUserRouteCode.get("RouteCode").toString();
        }
        return routeCode;
    }
}
